package com.chuanyang.driverh.mainhome;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.bean.AssignGoodData;
import com.chuanyang.driverh.bean.Waybill;
import com.chuanyang.driverh.response2.ResultAllotGoods;
import com.chuanyang.driverh.response2.ResultGoodsAllotTop;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.FinishEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class GoodsAssignWeightNumActivity extends BaseTitleActivity {
    private RadioGroup rg_top;
    private RadioButton rb0, rb1, rb2;
    private CheckBox cb_all;
    private String orderId;
    private TextView tv_clear, tv_choose_driver, tv_order_no;
    private OrderDetailData orderDetail;
    private LinearLayout ll_container;
    Waybill waybill;
    AssignGoodData goodsData;

    private List<View> list = new ArrayList<View>();

    @Override
    protected int getContentResId() {
        return R.layout.home_act_assign_goods_weight_num;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        rg_top = (RadioGroup) findViewById(R.id.rg_top);
        rb0 = (RadioButton) findViewById(R.id.rb0);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        rb2 = (RadioButton) findViewById(R.id.rb2);
        cb_all = (CheckBox) findViewById(R.id.cb_all);
        tv_clear = (TextView) findViewById(R.id.tv_clear);
        tv_choose_driver = (TextView) findViewById(R.id.tv_choose_driver);
        tv_order_no = (TextView) findViewById(R.id.tv_order_no);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);

    }

    @Override
    protected void initData() {
        rb0.setText("0" + "\n" + "应分配重量");
        rb1.setText("0" + "\n" + "已分配重量");
        rb2.setText("0" + "\n" + "余分配重量");
        setBackImg();
        getTitleTextView().setText("货物分配");
        orderId = getIntent().getStringExtra("data");
        tv_order_no.setText(orderId);
        getOrderdatail();
        getTopWeight();
    }


    @Override
    protected void initListener() {
        rb0.setOnClickListener(this);
        rb1.setOnClickListener(this);
        rb2.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        tv_choose_driver.setOnClickListener(this);
        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkChange(isChecked);

            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rb0:
                break;
            case R.id.rb1:
                break;
            case R.id.rb2:
                break;
            case R.id.tv_clear:
                if (cb_all.isChecked()){
                    cb_all.setChecked(false);
                }else {
                    if (list!=null && list.size()>0){
                        for (int i=0;i<list.size();i++){
                            ((ImageView) (list.get(i).findViewById(R.id.iv_assign))).setSelected(false);
                            ((EditText) (list.get(i).findViewById(R.id.et_num))).setText("");
                            ((EditText) (list.get(i).findViewById(R.id.et_assign_weight))).setText("");
                            ((EditText) (list.get(i).findViewById(R.id.et_num))).setEnabled(false);
                            ((EditText) (list.get(i).findViewById(R.id.et_assign_weight))).setEnabled(false);
                        }
                    }
                }
                break;
            case R.id.tv_choose_driver:
                try {
                    checkGoods();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void checkGoods() {
        if (list != null && list.size() > 0) {
            goodsData=new AssignGoodData();
            ArrayList<AssignGoodData.WaybillDetailsData> waybillDetails=new ArrayList<>();
            for (int i = 0; i < list.size();i++){
                if ( ((ImageView) (list.get(i).findViewById(R.id.iv_assign))).isSelected()){
                    AssignGoodData.WaybillDetailsData waybillDetail=new AssignGoodData.WaybillDetailsData();
                    waybillDetail.setOrderdetailId(orderDetail.getDetailList().get(i).getOrderDetailId());
                    EditText etWeight=(EditText) (list.get(i).findViewById(R.id.et_assign_weight));
                    EditText etNum=(EditText) (list.get(i).findViewById(R.id.et_num));
                    if (StringUtil.isBlank( etWeight.getText().toString().trim())){
                        PrintUtil.toast(activityContext,"请填写所选货物的重量");
                        return;
                    }else if(Double.parseDouble(etWeight.getText().toString().trim())==0){
                        PrintUtil.toast(activityContext,"请填写所选货物的重量");
                        return;
                    }else if(etNum.getText().toString().trim().length()>0 && Double.parseDouble(etNum.getText().toString().trim())==0){
                        PrintUtil.toast(activityContext,"分配数量不能是0");
                    } else{
                        waybillDetail.setDetailsWeight(etWeight.getText().toString().trim());
                        if (StringUtil.isBlank(etNum.getText().toString().trim())){
//                            waybillDetail.setDetailsNum(Integer.parseInt(etNum.getText().toString().trim()));
                        }else {
                            waybillDetail.setDetailsNum(Integer.parseInt(etNum.getText().toString().trim()));
                        }

                    }
                    waybillDetails.add(waybillDetail);

                }
            }

            if (waybillDetails.size()>0){
                goodsData.setWaybillDetails(waybillDetails);
                startActivityForResult(new Intent(activityContext,ChooseDriverActivity.class),1);
            }else{
                PrintUtil.toast(activityContext,"请先选择货物分配");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && !StringUtil.isBlank(data.getStringExtra("data"))) {
            goodsData.setDriverId(Integer.parseInt(data.getStringExtra("data")));
            waybill = new Waybill();
            waybill.setOrderId(orderDetail.getOrderId() + "");
            waybill.setWaybillParams(new ArrayList<AssignGoodData>());
            waybill.getWaybillParams().add(goodsData);
            postAssignInfo(waybill);
        }

    }

    private void postAssignInfo(final Waybill waybill) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
//        Map<String,String> params=new HashMap<String, String>();

        MyHttpUtil.AllotWaybill(activityContext, waybill, new MyCallback<ResultAllotGoods>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ResultAllotGoods result, int id) {
                if (result.getCode() == ConstUtil.OK) {
//                    PrintUtil.toast(activityContext,"货物分配成功");
                    EventBusUtil.postEvent(new RefleshFragEvent(2));
                    initData();
                    cb_all.setChecked(false);
                    if (result.getData() != null)
                        startActivity(new Intent(activityContext, CarPlanSuccessActivity.class).putExtra("data", result.getData() + ""));
                } else {
//                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });
    }

    private void getOrderdatail() {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("orderId", orderId);
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.selectOrderMsgById(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    try {
                        hideActivityLoading();
                        orderDetail = result.getData();
                        fillView(orderDetail);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });
    }

    private void getTopWeight() {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderId", orderId);
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.getDispatchInfoByOrderId(activityContext, params, new MyCallback<ResultGoodsAllotTop>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ResultGoodsAllotTop result, int id) {
                if (result.getCode() == ConstUtil.OK) {
//                    fillView(orderDetail);

                    try {
                        fillTop(result.getData());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    PrintUtil.toast(activityContext, result.getMsg());
                }
            }
        });


    }

    private void fillTop(ResultGoodsAllotTop.DataBean data) {
        rb0.setText(StringUtil.getDouble(data.getSumDetailsWeight() + "") + "\n" + "应分配重量");
        rb1.setText(StringUtil.getDouble(data.getThenDispatchSumWeigth() + "") + "\n" + "已分配重量");
        rb2.setText(StringUtil.getDouble(data.getSurplusSumWeight() + "") + "\n" + "余分配重量");
    }

    private void fillView(OrderDetailData orderDetail) {
        if (orderDetail == null) return;
        list.clear();
        tv_order_no.setText(orderDetail.getOrderNo());
        if (ll_container.getChildCount()>0){
            ll_container.removeAllViews();
        }

        if (orderDetail.getDetailList() != null && orderDetail.getDetailList().size() > 0) {
            for (int i = 0; i < orderDetail.getDetailList().size(); i++) {
                View view = View.inflate(activityContext, R.layout.home_item_assign_goods_num, null);
                ll_container.addView(view, new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                list.add(view);
            }
        }

        if (list.size() > 0) {
            setViewData();
            setListener();
        }
    }

    private void setViewData() {
        for (int i = 0; i < list.size(); i++) {
            ((TextView) (list.get(i).findViewById(R.id.tv_goods_name))).setText(orderDetail.getDetailList().get(i).getGoodsName());
            ((TextView) (list.get(i).findViewById(R.id.tv_goods_stand))).setText(orderDetail.getDetailList().get(i).getGoodsStandard());

            if (Double.parseDouble(orderDetail.getDetailList().get(i).getSurplusNum()) > 0) {
                ((TextView) (list.get(i).findViewById(R.id.tv_num))).setText("数量:" + orderDetail.getDetailList().get(i).getSurplusNum() + "件");
            } else {
                ((TextView) (list.get(i).findViewById(R.id.tv_num))).setText("数量:" + "0件");
            }
            if (Double.parseDouble(orderDetail.getDetailList().get(i).getSurplusWeight()) > 0) {
                ((TextView) (list.get(i).findViewById(R.id.tv_weight_left))).setText("重量:" + StringUtil.getDouble(orderDetail.getDetailList().get(i).getSurplusWeight()) + "t");
            } else {
                ((TextView) (list.get(i).findViewById(R.id.tv_weight_left))).setText("重量:" + "0t");
            }
        }
    }

    private void setListener() {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                final int j=i;
                ((ImageView) (list.get(j).findViewById(R.id.iv_assign))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((ImageView) v).setSelected(!v.isSelected());
                        setEditText(j, ((ImageView) v).isSelected());
                        if ( ((ImageView) v).isSelected()){
                            ((EditText) (list.get(j).findViewById(R.id.et_num))).setEnabled(true);
                            ((EditText) (list.get(j).findViewById(R.id.et_assign_weight))).setEnabled(true);
                        }else {
                            ((EditText) (list.get(j).findViewById(R.id.et_num))).setEnabled(false);
                            ((EditText) (list.get(j).findViewById(R.id.et_assign_weight))).setEnabled(false);

                        }
                    }
                });

                ((LinearLayout) (list.get(j).findViewById(R.id.ll_div))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!((ImageView) (list.get(j).findViewById(R.id.iv_assign))).isSelected()){
                            PrintUtil.toast(activityContext,"请先勾选左边的选择框再输入");
                        }
                    }
                });


            }
        }
    }

    private void checkChange(boolean isChecked) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ((ImageView) (list.get(i).findViewById(R.id.iv_assign))).setSelected(isChecked);
                setEditText(i,isChecked);

                if ( isChecked){
                    ((EditText) (list.get(i).findViewById(R.id.et_num))).setEnabled(true);
                    ((EditText) (list.get(i).findViewById(R.id.et_assign_weight))).setEnabled(true);
                }else {
                    ((EditText) (list.get(i).findViewById(R.id.et_num))).setEnabled(false);
                    ((EditText) (list.get(i).findViewById(R.id.et_assign_weight))).setEnabled(false);

                }
            }
        }
    }

    private void setEditText(int j,boolean checked){
        if (checked) {
            if (Double.parseDouble(orderDetail.getDetailList().get(j).getSurplusNum()) > 0) {
                ((EditText) (list.get(j).findViewById(R.id.et_num))).setText(orderDetail.getDetailList().get(j).getSurplusNum());
            } else {
                ((EditText) (list.get(j).findViewById(R.id.et_num))).setText("");
            }

            if (Double.parseDouble(orderDetail.getDetailList().get(j).getSurplusWeight()) > 0) {
                ((EditText) (list.get(j).findViewById(R.id.et_assign_weight))).setText(orderDetail.getDetailList().get(j).getSurplusWeight());
            } else {
                ((EditText) (list.get(j).findViewById(R.id.et_assign_weight))).setText("");
            }
        } else {
            ((EditText) (list.get(j).findViewById(R.id.et_num))).setText("");
            ((EditText) (list.get(j).findViewById(R.id.et_assign_weight))).setText("");
        }
    }


    public void onEventMainThread(FinishEvent event) {
        if (event.getIndex() == 1) {
            finish();
        }
    }
}
